package com.minsf.springbootinit.judge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.minsf.springbootinit.judge.codesandbox.CodeSandbox;
import com.minsf.springbootinit.judge.codesandbox.model.ExecuteCodeRequest;
import com.minsf.springbootinit.judge.codesandbox.model.ExecuteCodeResponse;

/**
 * @Description
 * @Author minify
 * @Date 2024/3/9 12:43
 * @Project oj-backend
 */
public class RemoteCodeSandbox implements CodeSandbox {

    public static final String AUTH_REQUEST_HEADER = "auth";

    public static final String AUTH_REQUEST_SECRET = "secret";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        System.out.println("远程代码沙箱");
        String url = "http://localhost:8090/executeCode";
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .body(json)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .execute()
                .body();

        System.out.println(responseStr);
        if (StrUtil.isBlank(responseStr)) {
            throw new RuntimeException("远程沙箱执行失败");
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}
